<?
class logRotator extends errorHandler{

	public $pathinfo=NULL;
	public $file=NULL;
	public $notify=array();
	public $zip=true;
	public $output="";
	public $sendNotification=true;


	public function __construct($log_file=NULL, $recips=NULL){
		parent::__construct();
		$this->setLogDirectory($log_file);
		$this->setAllRecipients($recips);
	}

	/* Set's the Log Directory to rotate the logs */
	/* Returns boolean. */
	public function setLogDirectory($log_file=NULL){
		$result=false;
		$this->file=(@file_exists($log_file)&&$log_file!==NULL)?$log_file:$this->config->log;
		$this->pathinfo=@pathinfo($this->file);
		return(@file_exists($this->file));
	}

	/* Set's the recipients in the notify array */
	/* Returns void */
	public function addRecipient($recip=NULL){
		if($recips!==NULL){
			$this->notify[]=$recip;
		}
	}
	public function setAllRecipients($recips=NULL){
		$this->notify=($recips===NULL)?$this->config->admin:$recips;
	}

	public function rotate(){
		$result=false;
		$dir=$this->pathinfo["dirname"];
		$file=$this->pathinfo["filename"];
		$ext=$this->pathinfo["extension"];
		if(@file_exists($dir)){
			$zipfile=$file."_".date("Ymd-his");
			$cmd='find '.$dir.' -name '.$file.'\*.'.$ext.' -not -name '.$file.'.'.$ext.' -print | zip '.$dir.'/'.$zipfile.' -@';
			print("<p><strong>Running Command:</strong> $cmd</p>");
			@exec($cmd,$output,$result);
			$cmd='find '.$dir.' -name '.$file.'\*.'.$ext.' -not -name '.$file.'.'.$ext.' -exec rm -f {} \;';
			print("<p><strong>Running Command:</strong> $cmd</p>");
			@exec($cmd);
			$this->output="";
			for($c=0;$c<count($output);$c++) {
				$this->output.="{$output[$c]}\n\n";
			}
			if($this->sendNotification){
				for($c=0;$c<count($this->notify);$c++) {
					print("<p><strong>Emailing:</strong> {$this->notify[$c]["email"]}</p>");
					$message=($result)?"The following log files have been zipped and are ready for backup (".date("d/m/Y H:i:s").")":"There was an error trying to zip the following log's files ({$this->file}) at ".date("d/m/Y H:i:s").":";
					$headers=	'From: '.$this->config->serverEmail["email"]."\r\n".
								'Reply-To: '.$this->config->serverEmail["email"]."\r\n".
								'X-Mailer: PHP/'.phpversion();
					@mail($this->notify[$c]["email"],"Gravy Log Rotation Performed","$message:\n\n{$this->output}",$headers);
				}
			}
		}else{
			print("<p><strong>Directory doesn't exist:</strong> $dir</p>");
			print("<p><strong>File:</strong> {$this->file}</p>");
		}
		return($result);
	}
};
?>